#!/bin/bash

echo "🚀 开始部署 webook 项目到 Kubernetes..."

# 检查 Docker 是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker 未运行，请先启动 Docker"
    exit 1
fi

# 检查 Kubernetes 集群状态
if ! kubectl cluster-info > /dev/null 2>&1; then
    echo "❌ Kubernetes 集群未运行，请先启动集群"
    exit 1
fi

echo "✅ Docker 和 Kubernetes 状态正常"

# 构建 Docker 镜像
echo "🔨 构建 Docker 镜像..."
docker build -t webook:latest .

if [ $? -ne 0 ]; then
    echo "❌ Docker 镜像构建失败"
    exit 1
fi

echo "✅ Docker 镜像构建成功"

# 检查镜像是否存在
if ! docker images | grep -q "webook.*latest"; then
    echo "❌ 镜像构建失败，未找到 webook:latest"
    exit 1
fi

# 部署到 Kubernetes
echo "📦 部署到 Kubernetes..."
kubectl apply -f k8s-webook-deployment.yaml

if [ $? -ne 0 ]; then
    echo "❌ Kubernetes 部署失败"
    exit 1
fi

echo "✅ Kubernetes 部署成功"

# 等待 Pod 启动
echo "⏳ 等待 Pod 启动..."
kubectl wait --for=condition=ready pod -l app=webook --timeout=300s

if [ $? -ne 0 ]; then
    echo "❌ Pod 启动超时"
    kubectl get pods -l app=webook
    kubectl describe pods -l app=webook
    exit 1
fi

echo "✅ Pod 启动成功"

# 获取服务信息
echo "📊 部署状态："
kubectl get pods -l app=webook
kubectl get services -l app=webook

# 获取 NodePort
NODEPORT=$(kubectl get service webook-service -o jsonpath='{.spec.ports[0].nodePort}')
echo ""
echo "🎉 部署完成！"
echo "📱 访问地址: http://$(hostname -I | awk '{print $1}'):$NODEPORT"
echo "🔍 健康检查: http://$(hostname -I | awk '{print $1}'):$NODEPORT/health"
echo ""
echo "📝 常用命令："
echo "  查看 Pod 状态: kubectl get pods -l app=webook"
echo "  查看服务状态: kubectl get services -l app=webook"
echo "  查看日志: kubectl logs -l app=webook"
echo "  删除部署: kubectl delete -f k8s-webook-deployment.yaml"
